//
//  SNSManager.m
//  PUDemo
//
//  Created by JK.Peng on 13-2-22.
//  Copyright (c) 2013年 njut. All rights reserved.
//

#import "SNSManager.h"
#import "WBEngineSina.h"
#import "WBEngineTX.h"
#import "QZoneEngine.h"
#import "OFEngineManager.h"


static SNSManager * sharedSNSManager;

@implementation SNSManager

- (void)dealloc
{
    RELEASE_SAFELY(_requestsArray);
    [super dealloc];
}

+ (SNSManager *)sharedManager
{
    if (!sharedSNSManager) {
        sharedSNSManager = [[SNSManager alloc] init];
    }
    return sharedSNSManager;
}

- (id)init
{
    self = [super init];
    if (self) {
        _requestsArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

#pragma mark - public method
- (OFEngine *)getOFEngineByOFType:(OFTypeE)type
{
    OFEngine * engine = nil;
    switch (type) {
        case kOFTypeSina:
            engine = PUGetOFEngineForSina;
            break;
        case kOFTypeTX:
            engine = PUGetOFEngineForTx;
            break;
        case kOFTypeQZone:
            engine = PUGetOFEngineForQZone;
            break;
        default:
            return nil;
    }
    engine.delegate = self;
    return engine;
}

- (void)cancelRequestForDelegate:(id<SNSManagerDelegate>)delegate
{
    for (int i = [_requestsArray count]-1; i >= 0; i--) {
        NSDictionary * dict = [_requestsArray objectAtIndex:i];
        if (delegate == [dict objectForKey:@"delegate"]) {
            [_requestsArray removeObjectAtIndex:i];
            break;
        }
    }
}

/**
 * @description sina sso回调方法，官方客户端完成sso授权后，回调唤起应用，应用中应调用此方法完成sso登录
 * @param url: 官方客户端回调给应用时传回的参数，包含认证信息等
 * @return YES
 */
- (BOOL)handleOpenCallbackURL:(NSURL *)url
{
    for (NSDictionary *dic in _requestsArray) {
        OFEngine * engine = [dic objectForKey:@"engine"];
        
        SNSManagerRequestTypeE type = [[dic objectForKey:@"requestType"] integerValue];
        if ([engine isKindOfClass:[WBEngineSina class]] && type==SNSManagerRequestTypeLogin) {
            [(WBEngineSina *)engine handleOpenURL:url];
            break;
        }
    }
    return YES;
}

#pragma mark - pivate
- (NSInteger)getIndexOfOFRequestWithEngine:(OFEngine *)engine
{
    for (NSInteger i = 0; i < [_requestsArray count]; i++) {
        NSDictionary * dict = [_requestsArray objectAtIndex:i];
        if ([dict objectForKey:@"engine"] == engine) {
            return i;
        }
    }
    return NSNotFound;
}

- (void)addOFRequestWithEngine:(OFEngine *)engine
                         weibo:(OFTypeE)wbType
                   requestType:(SNSManagerRequestTypeE)requestType
                      delegate:(id<SNSManagerDelegate>)delegate
{
    NSMutableDictionary  *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    if (engine) {
        [dict setObject:engine forKey:@"engine"];
    }
    [dict setObject:[NSNumber numberWithInt:wbType] forKey:@"wbType"];
    [dict setObject:[NSNumber numberWithInt:requestType] forKey:@"requestType"];
    if (delegate) {
        [dict setObject:delegate forKey:@"delegate"];
    }
    [_requestsArray addObject:dict];
}


#pragma mark - login or logout
- (void)loginFor:(OFTypeE)type withDelegate:(id<SNSManagerDelegate>)delegate
{
    OFEngine * engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeLogin
                        delegate:delegate];
    
    [engine logIn];
}
- (void)logoutFor:(OFTypeE)type withDelegate:(id<SNSManagerDelegate>)delegate
{
    OFEngine * engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeLogout
                        delegate:delegate];
    [engine logOut];
}
- (BOOL)isLoggedInFor:(OFTypeE)type
{
    return [[self getOFEngineByOFType:type] isLoggedIn];
}

- (void)requestUserProfile:(id<SNSManagerDelegate>)delegate type:(OFTypeE)type;
{
    OFEngine  *engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeUserProfile
                        delegate:delegate];
    if (type == kOFTypeSina) {
        WBEngineSina *sina = (WBEngineSina *)engine;
        [sina requestUserProfile];
    }else if(type == kOFTypeTX){
        WBEngineTX *tx = (WBEngineTX *)engine;
        [tx requestUserProfile];
    }else if(type == kOFTypeQZone){
        QZoneEngine *qzone = (QZoneEngine *)engine;
        [qzone requestUserProfile];
    }

}

- (void)sendContentWithText:(NSString *)text
                      image:(UIImage *)image
                   delegate:(id<SNSManagerDelegate>)delegate
                    forType:(OFTypeE)type
{
    OFEngine  *engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeSendContent
                        delegate:delegate];
    [engine sendWeiBoWithText:text image:image];
}

- (void)shareToQZoneWithTitle:(NSString *)title
                      comment:(NSString *)commentText
                     titleUrl:(NSString *)titleUrl
                      summary:(NSString *)summary
                        image:(UIImage *)image
                     delegate:(id<SNSManagerDelegate>)delegate
                      forType:(OFTypeE)type
{
    OFEngine  *engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeSendContent
                        delegate:delegate];
    [(QZoneEngine *)engine shareToQZoneWithTitle:title
                                         comment:commentText
                                        titleUrl:titleUrl
                                         summary:summary
                                           image:image];
    
    
}

- (void)shareToQZoneWithTitle:(NSString *)title
                      comment:(NSString *)commentText
                     titleUrl:(NSString *)titleUrl
                      summary:(NSString *)summary
                     imageUrl:(NSString *)imageUrl
                     delegate:(id<SNSManagerDelegate>)delegate
                      forType:(OFTypeE)type
{
    OFEngine  *engine = [self getOFEngineByOFType:type];
    [self addOFRequestWithEngine:engine
                           weibo:type
                     requestType:SNSManagerRequestTypeSendContent
                        delegate:delegate];
    
    [(QZoneEngine *)engine shareToQZoneWithTitle:title
                                         comment:commentText
                                        titleUrl:titleUrl
                                         summary:summary
                                        imageUrl:imageUrl];
}

#pragma mark - OFEngineDelegate
- (void)engineAlreadyLoggedIn:(OFEngine *)engine
{
    [self engineDidLogIn:engine];
}

- (void)engineDidLogIn:(OFEngine *)engine
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        OFTypeE  type = [[requestDict objectForKey:@"wbType"] intValue];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        if ([delegate respondsToSelector:@selector(snsManagerLoginDidSuccessFor:)]) {
            [delegate snsManagerLoginDidSuccessFor:type];
        }
        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }
}

- (void)engine:(OFEngine *)engine didFailToLogInWithError:(NSError *)error;
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        OFTypeE  type = [[requestDict objectForKey:@"wbType"] intValue];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        if ([delegate respondsToSelector:@selector(snsManagerLoginDidFailFor:)]) {
            [delegate snsManagerLoginDidFailFor:type];
        }
        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }
}

- (void)engineDidLogOut:(OFEngine *)engine
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        OFTypeE  type = [[requestDict objectForKey:@"wbType"] intValue];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        if ([delegate respondsToSelector:@selector(snsManagerLogoutDidFinishFor:)]) {
            [delegate snsManagerLogoutDidFinishFor:type];
        }
        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }
}

- (void)engineNotAuthorized:(OFEngine *)engine
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        if ([delegate respondsToSelector:@selector(snsManagerAuthorizeExpired)]) {
            [delegate snsManagerAuthorizeExpired];
        }
        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }

}

- (void)engineAuthorizeExpired:(OFEngine *)engine
{
    [self engineNotAuthorized:engine];
}

- (void)engine:(OFEngine *)engine requestDidFailWithError:(NSError *)error
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        OFTypeE  type = [[requestDict objectForKey:@"wbType"] intValue];
        SNSManagerRequestTypeE requestType = [[requestDict objectForKey:@"requestType"] intValue];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        
        if (requestType == SNSManagerRequestTypeUserProfile) {
            if ([delegate respondsToSelector:@selector(snsManagerUserProfileDidFailFor:)]) {
                [delegate snsManagerUserProfileDidFailFor:type];
            }
        }else if (requestType == SNSManagerRequestTypeSendContent) {
            if ([delegate respondsToSelector:@selector(snsManagerShareContentDidFailFor:withError:)]) {
                [delegate snsManagerShareContentDidFailFor:type withError:SNSManagerErrorTypeServer];
            }
        }else if (requestType == SNSManagerRequestTypeShortenUrl){
            if ([delegate respondsToSelector:@selector(snsManagerShortenUrlDidFailFor:)]) {
                [delegate snsManagerShortenUrlDidFailFor:type];
            }
        }

        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }
}

- (void)engine:(OFEngine *)engine requestDidSucceedWithResult:(id)result
{
    NSInteger index = [self getIndexOfOFRequestWithEngine:engine];
    if (index != NSNotFound) {
        NSDictionary * requestDict = [_requestsArray objectAtIndex:index];
        OFTypeE  type = [[requestDict objectForKey:@"wbType"] intValue];
        SNSManagerRequestTypeE requestType = [[requestDict objectForKey:@"requestType"] intValue];
        id<SNSManagerDelegate> delegate = [requestDict objectForKey:@"delegate"];
        
        if (requestType == SNSManagerRequestTypeUserProfile) {
            if ([delegate respondsToSelector:@selector(snsManagerUserProfileDidSuccessFor:withResult:)]) {
                [delegate snsManagerUserProfileDidSuccessFor:type withResult:result];
            }
        }else if (requestType == SNSManagerRequestTypeSendContent) {
            if ([delegate respondsToSelector:@selector(snsManagerShareContentDidSuccessFor:weiboId:)]) {
                NSString  *weiboId = nil;
                if (type == kOFTypeSina) {
                    weiboId = [BUGetObjFromDict(@"id", result, [NSNumber class]) stringValue];
                }else if(type == kOFTypeTX){
                    NSDictionary  *data = BUGetObjFromDict(@"data", result, [NSDictionary class]);
                    weiboId = BUGetObjFromDict(@"id", data, [NSString class]);
                }else if(type == kOFTypeQZone){
                    weiboId = [BUGetObjFromDict(@"share_id", result, [NSNumber class]) stringValue];
                }
                
                [delegate snsManagerShareContentDidSuccessFor:type weiboId:weiboId];
            }
        }else if (requestType == SNSManagerRequestTypeShortenUrl){
            if ([delegate respondsToSelector:@selector(snsManagerShortenUrlDidSuccessFor:withResult:)]) {
                [delegate snsManagerShortenUrlDidSuccessFor:type withResult:result];
            }
        }
        
        
        if ([_requestsArray count]>index) {
            [_requestsArray removeObjectAtIndex:index];
        }
    }
}

- (void)covertToShotURL:(NSString *)longURL withDelegate:(id<SNSManagerDelegate>)delegate{
    OFEngine  *engine = [self getOFEngineByOFType:kOFTypeSina];
    [self addOFRequestWithEngine:engine
                           weibo:kOFTypeSina
                     requestType:SNSManagerRequestTypeShortenUrl
                        delegate:delegate];
    WBEngineSina *sina = (WBEngineSina *)engine;
    [sina covertToShort_urlWithLongUrl:[longURL URLEncodedString]];

}
@end
